package com.markerhub.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.markerhub.common.dto.EditDto;
import com.markerhub.common.dto.LoginDto;
import com.markerhub.common.dto.RegistDto;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.User;
import com.markerhub.service.UserService;
import com.markerhub.util.JwtUtils;
import com.markerhub.util.ShiroUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Date;


//@Controller：用于定义控制器类，在spring 项目中由控制器负责将用户发来的URL请求转发到对应的服务接口（service层）
//@ResponseBody：表示该方法的返回结果直接写入HTTP response body中，一般在异步获取数据时使用，用于构建RESTful的api。
//加上@responsebody后返回结果不会被解析为跳转路径，而是直接写入HTTP response body中。
//↓@Controller+@ResponseBody
@RestController
public class AccountController {

    @Autowired
    UserService userService;

    @Autowired
    JwtUtils jwtUtils;
    //Result类返回实体类为主，附属错误代码
    @RequestMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response, HttpServletRequest request){
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        Assert.notNull(user,"用户不存在");//断言拦截
        //判断账号密码是否错误 因为是md5加密所以这里md5判断
        if(!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
            //密码不同则抛出异常
            return Result.faile("密码不正确");
        }
        String jwt = jwtUtils.generateToken(user.getId());
        System.out.println("------------------------------------------------"+user);
;
        //将token 放在我们的header里面
        response.setHeader("Authorization",jwt);
        response.setHeader("Access-Control-Expose-Headers","Authorization");

        return Result.succ(MapUtil.builder()
                .put("id",user.getId())
                .put("username",user.getUsername())
                .put("avatar",user.getAvatar())
                .put("email",user.getEmail()).map()

        );
    }

    //注册
    @PostMapping("/regist")
    public  Result regist(@Validated @RequestBody RegistDto registDto){
        //registDto 拿来接收前端发送的数据 自己创建dto类
        System.out.println(registDto.getPwd());
        System.out.println(registDto.getPwd1());
        System.out.println(registDto.getUsername());
        System.out.println(registDto.getEmail());
        System.out.println(registDto.getValue3());

        //这里偷懒通过协议同意来进行创建实体类注册
        if(registDto.getValue3().equals("true")){
            User user = new User();

            user.setUsername(registDto.getUsername())
                    .setEmail(registDto.getEmail())
                    .setPassword(SecureUtil.md5(registDto.getPwd()))
                    .setCreated(LocalDateTime.now())
                    .setAvatar("https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png")
                    .setStatus(0);//
            System.out.println(user);
            //注册指令并返回注册成功
            userService.saveOrUpdate(user);
            return Result.succ("注册成功");
        }else {
            return Result.faile("请同意协议");
        }


    }


    //需要认证权限才能退出登录
    @RequiresAuthentication
    @RequestMapping("/logout")
    public Result logout() {
        //退出登录
        SecurityUtils.getSubject().logout();
        System.out.println("123");
        return Result.succ("注销成功");
    }

    @RequiresAuthentication
    @RequestMapping("/editpwd")
    public Result editpawd(@Validated @RequestBody EditDto editDto) {
        //修改密码
        System.out.println("***********************************************"+editDto);
        System.out.println("**************md5*************************"+SecureUtil.md5(editDto.getOldpwd()));
        User user = userService.getById( ShiroUtil.getProfile().getId().longValue());
        System.out.println("**************user***********************"+user.getPassword());

        if(user.getPassword().equals(SecureUtil.md5(editDto.getOldpwd())) ){
            System.out.println(user);

            user.setPassword(SecureUtil.md5(editDto.getPwd()));
            userService.saveOrUpdate(user);
            SecurityUtils.getSubject().logout();
            //System.out.println("123");
            return Result.succ("成功,请重新登录");
        }else {
            return Result.faile("旧密码错误");
        }

    }




}